import os
from io import BytesIO
from random import randint

from PIL import Image, ImageFont, ImageDraw

from Blogproject import settings


class Getcode():
    # 验证码有大小，几位
    def __init__(self,width=100,height = 40,len=4):
        self.width = width if width >50 else 100
        self.height = height if height > 40 else 40
        self.len = len if len > 4 else 4
        # 生成的字符串赋值给这个
        self._code = ''
        # 定义一个画笔
        self.__pen = None
    # 设置属性，可以调用

    @property
    def code(self):
        return self._code
    # 生成随机颜色
    def __randomcolor(self,low,heigh):
        res = (randint(low,heigh),randint(low,heigh),randint(low,heigh))
        return res

    def Randomstr(self):
    #     根据init里面的len,看需要循环几次
        num = ''
        for i in range(self.len):
            res = randint(0,9)
            num += str(res)
        # 下面是个字符串，所以可以根据索引来获取
        self._code = num

    # 画验证码
    def __drawcode(self):
    #     先拼接，得到字体，获取ｘｙ坐标，
    # 得到字体
        fontpath = os.path.join(settings.STATICFILES_DIRS[0],'font/01.TTF')
        # print(fontpath)
    #     获取一个字体的对象
        fontcode = ImageFont.truetype(fontpath,size=30,encoding='utf-8')
        # print(fontcode)
    #     得到一个字符的宽度
        perwidth = (self.width-20)/self.len
        # print(perwidth)
    #     循环画
        for i in range(self.len):
            x = 10 + i * perwidth + perwidth/4
            y = randint(5,self.height-20)
    #         画 def text(self, xy, text, font):
            self.__pen.text((x,y),self._code[i],font=fontcode,fill = self.__randomcolor(0,100))
    # 干扰点
    def __drawpoint(self):
    #     和画验证码一样,看需要画多少个点
        for i in range(200):
            x = randint(1,self.width-1)
            y = randint(1,self.height-1)
            self.__pen.point((x,y),fill =self.__randomcolor(60,160))
    # 干扰线
    def __drawline(self):
        for i in range(self.len):
            start = randint(1,self.width),randint(1,self.height-1)
            end = randint(1,self.width),randint(1,self.height-1)
    #         画
            self.__pen.line([start,end],fill = self.__randomcolor(100,200))


    def output(self):
        # 创建画布,画笔，产生验证码字符串，画验证码，画干扰点，画干扰线，返回图片
        img = Image.new('RGB',(self.width,self.height),self.__randomcolor(100,200))
        # 走了这一步，相当于知道了self._code的值
        # 产生画笔
        self.__pen = ImageDraw.Draw(img)
        # 画验证码是text.画点是point 画线是line

        self.Randomstr()
        # 下面这个函数相当于生成一个画笔
        self.__drawcode()
        # 画干扰点
        self.__drawpoint()
        # 干扰线
        self.__drawline()

        img.save('01.png','PNG')
#         默认不保存在本地，是以２二进制流的方式进行保存
#         创建buf对象，
        buf = BytesIO()
        img.save(buf,'PNG')
        # 得到的是字节
        res = buf.getvalue()
        # print(res)
        buf.close()
        return res




if __name__ == '__main__':
    m = Getcode()
    m.output()



